<?php


namespace KukePay\Tencent\AccessToken;


use KukePay\ExceptionHandler;
use KukePay\Kernel\Factory;
use KukePay\Tencent\Payment\Kernel\ConfigFactory;

class Application extends Factory
{
    private $uri = 'https://api.weixin.qq.com/cgi-bin/token';
    /**
     * 全局配置
     * @var array
     */
    private $config;

    /**
     * Application constructor.
     * @param ConfigFactory $config
     */
    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
        parent::__construct();
    }

    /**
     * 获取token
     * @return \Exception|ExceptionHandler|mixed|string
     */
    public function get()
    {
        try {
            $url = $this->uri . "?grant_type=client_credential&appid={$this->config->getAppId()}&secret={$this->config->getSecret()}";

            $response = $this->request->get($url)->getBody()->getContents();

            $response = json_decode($response, true);

            if (isset($response['access_token'])) {
                return $response;
            }

            throw new ExceptionHandler($response['errmsg']);
        } catch (ExceptionHandler $exception) {
            return $exception;
        }
    }

    /**
     * getJsApiTicket
     * @param $access_token
     * @return mixed|string
     */
    public function getJsApiTicket($access_token)
    {
        try {
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$access_token}";

            $response = $this->request->get($url)->getBody()->getContents();

            $response = json_decode($response, true);

            if (isset($response['ticket'])) {
                return $response;
            }
            throw new ExceptionHandler($response['errmsg']);
        } catch (ExceptionHandler $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * @return string
     */
    private function getJsApiTicketKey()
    {
        return 'swoole_pay_public_' . $this->config->getAppId() . '_getticket';
    }

    /**
     * @return string
     */
    private function getAccessTokenKey()
    {
        return 'swoole_pay_public_' . $this->config->getAppId() . '_access_token';
    }
}